<template>
  <div class="page">
    <DeptList @change="handleDeptChange" />
    <div style="flex: 1">
      <div>用户列表 {{ departmentName }}</div>
      <ProTable ref="proTableRef" :request="request" :is-auto="false">
        <template #tool>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="danger"> 删除 </el-button>
        </template>

        <el-table-column label="头像" prop="headImg">
          <template #default="{ row }">
            <el-avatar :src="row.headImg" alt="" />
          </template>
        </el-table-column>
        <el-table-column label="用户名" prop="username" />
        <el-table-column label="姓名" prop="name" />
        <el-table-column label="昵称" prop="nickName" />
        <el-table-column label="部门名称" prop="departmentName" />
        <el-table-column label="角色" prop="roleName" />
        <el-table-column label="状态" prop="status">
          <template #default="{ row }">
            <el-switch
              :modelValue="row.status"
              :active-value="1"
              :deactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column label="手机号码" prop="phone" />
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="default" text bg @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" text bg> 删除 </el-button>
          </template>
        </el-table-column>
      </ProTable>
    </div>
  </div>

  <Upsert
    ref="upsertRef"
    @success="handleDeptChange({ ids: departmentIds, name: departmentName })"
  />
</template>

<script>
import ProTable from "@/components/pro-table/index.vue";
import { getSysUserPage } from "@/api/sys";
import DeptList from "@/components/dept-list/index.vue";
import Upsert from "@/pages/sys/user/upsert.vue";

export default {
  name: "SysUser",

  components: {
    Upsert,
    DeptList,
    ProTable,
  },

  data() {
    return {
      departmentName: "", // 当前选择的部门名字
      departmentIds: [], // 当前选择的部门Id集合
    };
  },

  methods: {
    async request(query) {
      const { list, pagination } = await getSysUserPage({
        page: query.currentPage,
        size: query.pageSize,
        departmentIds: this.departmentIds, // 部门Id集合
      });

      return {
        list,
        total: pagination.total,
      };
    },

    handleDeptChange({ ids, name }) {
      this.departmentName = name;
      this.departmentIds = ids;
      // 让右侧的表格基于这份 ids 来调用接口获取数据
      this.$refs.proTableRef.refresh();
    },

    // 新增按钮点击
    handleAdd() {
      this.$refs.upsertRef.open();
    },
    // 编辑按钮点击
    handleEdit(row) {
      this.$refs.upsertRef.open(row);
    },
  },
};
</script>

<style scoped>
.page {
  display: flex;
}
</style>
